package controllers

import (
	"aaa123/cache"
	"aaa123/models"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户名或密码不能为空",
		}
		c.ServeJSON()
		return
	}
	uu := models.Useras{
		Username: username,
		Password: password,
	}
	err := models.DB.Debug().Where("username=?", username).Limit(1).Find(&uu).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}
	//if uu.ID != 0 {
	//	c.Data["json"] = map[string]interface{}{
	//		"code": 0,
	//		"msg":  "用户不存在",
	//	}
	//	c.ServeJSON()
	//	return
	//}
	key := fmt.Sprintf("uu_login_%d", models.Useras{}.ID)
	Count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if Count >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "密码错误三次拦截",
		}
		c.ServeJSON()
		return
	}
	cache.Rdb.Incr(cache.Ctx, key)
	if Count == 2 {
		cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
	}
	err = models.DB.Debug().Create(&uu).Error
	if uu.Password != password {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "登录失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "登录成功",
		}
		c.ServeJSON()
		return
	}

}
